package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.PropertyCloudServiceCastMessagePageDTO;
import com.itlong.cloud.POJO.PO.DeviceBusinessChangeLogPO;
import com.itlong.cloud.POJO.PO.PropertyCloudServiceCostMessageInfoPO;
import com.itlong.cloud.POJO.VO.operate.OperateBusinessChargeVO;
import com.itlong.cloud.POJO.VO.property.PropertyCloudServiceCostMessageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.property.dao.IPropertyCloudServiceCostMessageDao;
import com.itlong.cloud.property.service.IPropertyCloudServiceMessageCostService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.PageByVisitor;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *      物业—云服务费消息通知服务接口实现类。
 * <desc/>
 *
 * @createDate 2019/08/07.
 */
@Service
public class PropertyCloudServiceCostMessageServiceImpl implements IPropertyCloudServiceMessageCostService {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyCloudServiceCostMessageServiceImpl.class);

    @Autowired
    IPropertyCloudServiceCostMessageDao iPropertyCloudServiceCostMessageDao;

    @Autowired
    private MessageSender messageSender;

    /**
     * <desc>
     *      获取云服务费消息推送分页信息。
     * <desc/>
     *
     * @param  pageDTO 请求参数
     * @return
     * @author Juguang.S
     * @createDate 2019-08-07
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PageByVisitor<PropertyCloudServiceCostMessageVO> getMessageByPage(PropertyCloudServiceCastMessagePageDTO pageDTO) throws Exception{
        //将DTO转换为Map params
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(pageDTO);
        //分页类默认pageSize为20
        PageByVisitor<PropertyCloudServiceCostMessageVO> page = new PageByVisitor<>();
        page.getPage().setPageSize(pageDTO.getPageSize());
        page.getPage().setCurrentPage(pageDTO.getCurrentPage());
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());

        //查看该用户是否有审批权限

        //填充返回数据集
        List<PropertyCloudServiceCostMessageVO> list = iPropertyCloudServiceCostMessageDao.getMessageByPage(params);
//        list.forEach(cloudServiceCostMessageVO ->{
//            cloudServiceCostMessageVO.setChargeDetail(iPropertyCloudServiceCostMessageDao.getOrderDataInfo(cloudServiceCostMessageVO.getOrderId()));
//            cloudServiceCostMessageVO.setLastAmount(iPropertyCloudServiceCostMessageDao.getLastAmountbyBatchNumber(cloudServiceCostMessageVO.getBatchNumber()));
//        }
        //查看未读消息
        if (pageDTO.getMark() == 0){
            list.forEach(messageInfo ->{
                //消息类型为读取用户审核消息时
                if (messageInfo.getMessageType() == 2){
                    //统计当前项目下待审批的用户数量
                    Integer userAmount = iPropertyCloudServiceCostMessageDao.getProjectCheckCount(pageDTO.getProjectId());
                    messageInfo.setUserAmount(userAmount);
                }
            });
        }
        page.setRows(list,iPropertyCloudServiceCostMessageDao.getMessageByPageCount(params));
        params.put("mark",0);
        page.setVisitorCount(iPropertyCloudServiceCostMessageDao.getMessageByPageCount(params));
        return page;
    }

    /**
     * <desc>
     *      获取云服务费消息的详细信息。
     * <desc/>
     *
     * @param  messageId 消息ID
     * @param  loginUserId 用户ID
     * @return
     * @author Juguang.S
     * @createDate 2019-08-07
     */
    @Override
    public PropertyCloudServiceCostMessageVO getMessageInfo(String messageId,String loginUserId) {
        PropertyCloudServiceCostMessageVO cloudServiceCostMessageVO = iPropertyCloudServiceCostMessageDao.getMessageInfo(messageId,loginUserId);
        cloudServiceCostMessageVO.setChargeDetail(iPropertyCloudServiceCostMessageDao.getOrderDataInfo(cloudServiceCostMessageVO.getOrderId()));
        String amount =  iPropertyCloudServiceCostMessageDao.getLastAmountbyBatchNumber(cloudServiceCostMessageVO.getBatchNumber());
        cloudServiceCostMessageVO.setLastAmount(StringUtils.isNotEmpty(amount)?amount:"");
        return cloudServiceCostMessageVO;
    }

    /**
     * <desc>
     *      修改云服务费消息的状态。
     * <desc/>
     *
     * @param  messageId 消息ID 多个以逗号隔开
     * @param  type 修改类型 0删除 1修改状态为已读
     * @return
     * @author Juguang.S
     * @createDate 2019-08-07
     */
    @Override
    public void updateMessageInfo(String messageId, String type) {
        String[] messageArr = messageId.split(",");
        Map<String,Object> params = new HashMap<>();

        //查看该消息的消息类型
        PropertyCloudServiceCostMessageInfoPO messageInfoPO = iPropertyCloudServiceCostMessageDao.getMessageType(messageId);
        if (messageInfoPO != null && 2 == messageInfoPO.getMessageType()){
            Integer userAmount = iPropertyCloudServiceCostMessageDao.getProjectCheckCount(messageInfoPO.getProjectId());
            params.put("userAmount", userAmount);
        }
        params.put("messageArr",messageArr);
        params.put("type",type);
        iPropertyCloudServiceCostMessageDao.updateMessageInfo(params);
    }

    /**
     * <desc>
     *      保存定时任务的云服务费消息推送。
     * <desc/>
     *
     * @return
     * @author Juguang.S
     * @createDate 2019-08-08
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<Map<String,String>> savePushMessage() throws Exception{
        //查询项目的过期时间明细
        ArrayList<Map<String,Object>> rowsList = new ArrayList<>() ;
        List<Map<String,String>> returnList = new ArrayList<>();
        List<OperateBusinessChargeVO> list = iPropertyCloudServiceCostMessageDao.getProjectCloudServiceEndTimeInfo();
        //处理多条复用至新批次号并且未支付的情况
        List<OperateBusinessChargeVO> listBySome = iPropertyCloudServiceCostMessageDao.getProjectCloudServiceEndTimeInfoBySome();
        for(OperateBusinessChargeVO chargeVO : listBySome){
            Integer endDays = Integer.valueOf(iPropertyCloudServiceCostMessageDao.getCloudServiceCostEndTimeBySome(chargeVO.getOldBatchNumber().split(",")));
            if(endDays==1 || endDays==2 || endDays==3 || endDays==7 || endDays==15 || endDays==30 || endDays==60 || endDays==90){
                PropertyCloudServiceCostMessageInfoPO messageInfoPO = new PropertyCloudServiceCostMessageInfoPO();
                messageInfoPO.setEndDays(endDays.toString());
                messageInfoPO.setMark(0);
                messageInfoPO.setMessageId(LogicIdUtil.bussinessId());
                messageInfoPO.setProjectId(chargeVO.getProjectId());
                messageInfoPO.setOrderId(chargeVO.getOrderId());
                messageInfoPO.setCreateTime(new Date());
                messageInfoPO.setUpdateTime(new Date());
                messageInfoPO.setStatus(1);
                rowsList.add(SqlUtil.durableData(messageInfoPO, PlatformConstants.TABLE_SAVE));
                String projectId = chargeVO.getProjectId();
                Map<String,String> messageInfo = iPropertyCloudServiceCostMessageDao.getSendMessageInfo(projectId);
                if(null != messageInfo){
                    messageInfo.put("endDays",endDays.toString());
                    returnList.add(messageInfo);
                }
            }
        }

        //处理正常情况
        for(OperateBusinessChargeVO chargeVO : list){
            //查询批次号是否有未支付已被商务审核过的订单，若没有则不推送消息
            String orderId = iPropertyCloudServiceCostMessageDao.getIsExistNotPaymentOrderId(chargeVO.getBatchNumber());
            if(StringUtils.isEmpty(orderId)){
                continue;
            }
            Date endDate = DateUtil.fomatLongDate2(chargeVO.getEndTime());
            Date nowDate = DateUtil.fomatLongDate2(DateUtil.fomatDate(new Date(), "yyyy-MM-dd"));
            if(endDate.compareTo(nowDate)>0){
                //提醒规则按如下： 90天 60天 30天 15天 7天 3天 2天 1天提醒
                Integer endDays = DateUtil.differentDays(nowDate,endDate);
                if(endDays==1 || endDays==2 || endDays==3 || endDays==7 || endDays==15 || endDays==30 || endDays==60 || endDays==90){
                    PropertyCloudServiceCostMessageInfoPO messageInfoPO = new PropertyCloudServiceCostMessageInfoPO();
                    messageInfoPO.setEndDays(endDays.toString());
                    messageInfoPO.setMark(0);
                    messageInfoPO.setMessageId(LogicIdUtil.bussinessId());
                    messageInfoPO.setProjectId(chargeVO.getProjectId());
                    messageInfoPO.setOrderId(orderId);
                    messageInfoPO.setCreateTime(new Date());
                    messageInfoPO.setUpdateTime(new Date());
                    messageInfoPO.setStatus(1);
                    rowsList.add(SqlUtil.durableData(messageInfoPO, PlatformConstants.TABLE_SAVE));
                    String projectId = chargeVO.getProjectId();
                    Map<String,String> messageInfo = iPropertyCloudServiceCostMessageDao.getSendMessageInfo(projectId);
                    if(null != messageInfo){
                        messageInfo.put("endDays",endDays.toString());
                        returnList.add(messageInfo);
                    }
                }
            }
        }
        if(rowsList!=null && !rowsList.isEmpty()){
            iPropertyCloudServiceCostMessageDao.batchSave(rowsList);
        }
        return returnList;
    }

    /**
     * <desc>
     *      定时向未设置批次号的云对讲设备推送设备过期时间。
     * <desc/>
     *
     * @return
     * @author Juguang.S
     * @createDate 2020-02-27
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void pushCloudTalk() throws Exception {
        List<String> allProjectList = iPropertyCloudServiceCostMessageDao.getAllProjectId();
        for(String projectId : allProjectList){
            //需要排除的旧批次号集合
            List<String> oldBatchNumberArr = new ArrayList<>();
            //查询出需排除的旧批次集合
            List<String> oldBatchNumberList = iPropertyCloudServiceCostMessageDao.getOldBatchNumberByProjectId(projectId);
            for(String oldBatchNumbers : oldBatchNumberList){
                for(String oldBatchNumber : oldBatchNumbers.split(",")){
                    oldBatchNumberArr.add(oldBatchNumber);
                }
            }
            //获取项目下最近批次号过期时间
            String endTimeByProjectId = iPropertyCloudServiceCostMessageDao.getBatchNumberEndTimeByProjectId(projectId,oldBatchNumberArr.size()>0?oldBatchNumberArr:null);
            if(StringUtils.isNotEmpty(endTimeByProjectId)){
                List<Map<String, String>> allDeviceList = iPropertyCloudServiceCostMessageDao.getCloudTalkInfoByProjectId(projectId);
                List<DeviceBusinessChangeLogPO> changeLogPOS = new ArrayList<>();
                JSONArray jsonArray = new JSONArray();
                if(allDeviceList != null && !allDeviceList.isEmpty()) {
                    for (Map<String, String> map : allDeviceList) {
                        if(StringUtils.isEmpty(map.get("deviceUnique"))){
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("deviceUnique", map.get("deviceUnique"));
                        jsonArray.add(jsonObject);
                    }
                }
                if (!jsonArray.isEmpty()) {
                    DeviceBusinessChangeLogPO changeLogPO = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_DEVICE, jsonArray, projectId);
                    changeLogPOS.add(changeLogPO);
                }
                //向设备推送设备云对讲指令
                if (!changeLogPOS.isEmpty()) {
                    JSONObject dataJs = new JSONObject();
                    dataJs.put("data", changeLogPOS);
                    //云对讲
                    messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                            JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                            RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
                }
            }
        }
    }


}
